<?php

class UpdatePwdForm extends CFormModel
{
	public $oldPassword;
	public $newPassword;
	public $rePassword;
	public $memberModel;
	public $memberId;
	public $memberPwdAttr = 'worker_password';
	public $_identity;
	
	public function rules()
	{
		if (Yii::app()->adminUser->role == AdminUser::ROLE_OPERATOR) {
			return array(
				array('newPassword, rePassword', 'required'),
				array('newPassword', 'length', 'min'=>6),
				array('rePassword', 'compare', 'compareAttribute'=>'newPassword', 'message'=>'两次密码不同.'),
			);
		} else {
			return array(
				array('oldPassword,newPassword, rePassword', 'required'),
				array('oldPassword', 'authenticate'),
				array('newPassword', 'length', 'min'=>6),
				array('rePassword', 'compare', 'compareAttribute'=>'newPassword', 'message'=>'两次密码不同.'),
			);
		}
		
	}

	/**
	 * Declares attribute labels.
	 */
	public function attributeLabels()
	{
		return array(
			'oldPassword'=>'旧密码',
			'newPassword' => '新密码',
			'rePassword' => '重复密码',
		);
	}

	public function authenticate($attribute,$params)
	{
		if(!$this->hasErrors())
		{
			$member = $this->member;
			if($this->{$attribute} != $member->worker_password)
				$this->addError($attribute,'旧密码与原密码不符.');
		}
	}

	public function getMember() {
		if (!is_object($this->_identity)) {
			$memberModel = new $this->memberModel;
			$this->_identity = $memberModel->findByPk($this->memberId);
			if (!is_object($this->_identity)) throw new CHttpException(404,'用户未登录，请先登录');
		}
		return $this->_identity;
	}
	
	public function save() {
		$member = $this->member;
		$member->{$this->memberPwdAttr} = $this->newPassword;
		return $member->save();
	}
}
